package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FastDFSController {
    @PostMapping("/upload")
    public Result upload(MultipartFile file)  {
        try {
        if (file==null){
            throw new RuntimeException("文件不存在");
        }
        String originalFilename = file.getOriginalFilename();
        if (originalFilename==null){
            throw new RuntimeException("文件不存在");
        }
        String extname = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        byte[] content = new byte[0];

            content = file.getBytes();
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, content, extname);
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);
            for (String s : uploadResult) {
                System.out.println(s);
            }
            String url=FastDFSClient.getTrackerUrl()+uploadResult[0]+"/"+uploadResult[1];
            return new Result(true, StatusCode.OK,"文件上传成功",url);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"文件上传失败");
        }

    }
}
